package com.aote.entity.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.aote.mvc.event.Action;
import com.browsesoft.baseadapter.AdvancedSimpleEntity;
import com.browsesoft.dbtools.DBTools;

/**
 * 唯一性校验动作。在输入框上输入数据后，如果要对数据进行全局唯一性校验，使用该动作。
 */
public class OnlyOneValidAction extends Action {
	public void performAction(Element config, HttpServletRequest request,
			Map attrs) {
		// 得到模型
		AdvancedSimpleEntity model = (AdvancedSimpleEntity) component
				.getModel();
		// 从表里找除过自己外，有没有与给定名称相同的实体
		String table = model.getTableName();
		String id = model.getID();
		String name = config.getAttribute("attrname");
		if (config.hasAttribute("tablename")) {
			table = config.getAttribute("tablename");
		}
		String value = (String) attrs.get(name);
		if (config.hasAttribute("attrnamefield")) {
			name = config.getAttribute("attrnamefield");
		}
		String sql = "";
		if (config.hasAttribute("notid")) {
			sql = "select id from " + table + " where  " + name + " = '"
					+ value + "'";
		} else {
			sql = "select id from " + table + " where id <> '" + id + "' and "
					+ name + " = '" + value + "'";
		}
		try {
			String data[][] = DBTools.executeQueryWithTableHead(sql);
			// 有数据，提示错误
			if (data.length >= 2) {
				String msg = config.getAttribute("errormessage");
				model.getComponent().getPage().showMessage(msg);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
